package cn.stylefeng.guns.sys.modular.system.controller;

import cn.stylefeng.guns.base.pojo.page.LayuiPageInfo;
import cn.stylefeng.guns.sys.core.listener.WmhExcelListener;
import cn.stylefeng.guns.sys.core.util.JsonResult;
import cn.stylefeng.guns.sys.modular.system.entity.BtyWmh;
import cn.stylefeng.guns.sys.modular.system.mapper.BtyWmhMapper;
import cn.stylefeng.guns.sys.modular.system.model.params.BtyDbdkParam;
import cn.stylefeng.guns.sys.modular.system.model.params.BtyWmhParam;
import cn.stylefeng.guns.sys.modular.system.model.result.BtyWmhDto;
import cn.stylefeng.guns.sys.modular.system.model.result.BtyWmhResult;
import cn.stylefeng.guns.sys.modular.system.service.BtyWmhService;
import cn.stylefeng.roses.core.base.controller.BaseController;
import cn.stylefeng.roses.core.reqres.response.ResponseData;
import cn.stylefeng.roses.core.util.ToolUtil;
import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.List;


/**
 * 控制器
 *
 * @author liuy
 * @Date 2022-02-09 16:28:49
 */
@Controller
@RequestMapping("/btyWmh")
public class BtyWmhController extends BaseController {

    private String PREFIX = "/modular/system/btyWmh";

    @Autowired
    private BtyWmhService btyWmhService;
    @Resource
    private BtyWmhMapper wmhMapper;

    /**
     * 跳转到主页面
     *
     * @author liuy
     * @Date 2022-02-09
     */
    @RequestMapping("")
    public String index() {
        return PREFIX + "/btyWmh.html";
    }

    /**
     * 新增页面
     *
     * @author liuy
     * @Date 2022-02-09
     */
    @RequestMapping("/add")
    public String add() {
        return PREFIX + "/btyWmh_add.html";
    }

    /**
     * 编辑页面
     *
     * @author liuy
     * @Date 2022-02-09
     */
    @RequestMapping("/edit")
    public String edit() {
        return PREFIX + "/btyWmh_edit.html";
    }

    /**
     * 新增接口
     *
     * @author liuy
     * @Date 2022-02-09
     */
    @RequestMapping("/addItem")
    @ResponseBody
    public ResponseData addItem(BtyWmhParam btyWmhParam) {
        this.btyWmhService.add(btyWmhParam);
        return ResponseData.success();
    }

    /**
     * 编辑接口
     *
     * @author liuy
     * @Date 2022-02-09
     */
    @RequestMapping("/editItem")
    @ResponseBody
    public ResponseData editItem(BtyWmhParam btyWmhParam) {
        this.btyWmhService.update(btyWmhParam);
        return ResponseData.success();
    }

    /**
     * 删除接口
     *
     * @author liuy
     * @Date 2022-02-09
     */
    @RequestMapping("/delete")
    @ResponseBody
    public ResponseData delete(BtyWmhParam btyWmhParam) {
        this.btyWmhService.delete(btyWmhParam);
        return ResponseData.success();
    }

    /**
     * 查看详情接口
     *
     * @author liuy
     * @Date 2022-02-09
     */
    @RequestMapping("/detail")
    @ResponseBody
    public ResponseData detail(BtyWmhParam btyWmhParam) {
        BtyWmh detail = this.btyWmhService.getById(btyWmhParam.getId());
        return ResponseData.success(detail);
    }

    /**
     * 查询列表
     *
     * @author liuy
     * @Date 2022-02-09
     */
    @ResponseBody
    @RequestMapping("/list")
    public LayuiPageInfo list(BtyWmhParam btyWmhParam) {
        return this.btyWmhService.findPageBySpec(btyWmhParam);
    }

    /**
     * 导入excel
     */
    @RequestMapping("/import")
    @ResponseBody
    public Object addUsers(@RequestParam("file") MultipartFile file, BtyDbdkParam param) {
        JsonResult jsonResult = new JsonResult();
        if(ToolUtil.isEmpty(param.getZdrq())){
            jsonResult.setState(0);
            jsonResult.setErrmsg("请先选择制单日期！");
            return jsonResult;
        }
        //导入之前删掉之前的数据
        wmhMapper.delete(new QueryWrapper<>());
        String zdrq=param.getZdrq();
        try {
            WmhExcelListener basicExcelListener = new WmhExcelListener(btyWmhService);
            EasyExcel.read(file.getInputStream(), BtyWmhDto.class, basicExcelListener).sheet(0).headRowNumber(9).doRead();
            //导入成功之后生成外卖盒或者发热包凭证
            List<BtyWmhResult>list=btyWmhService.wmhList();
            for (BtyWmhResult btyWmhResult : list) {
                String yaoma=btyWmhResult.getYaoma();
                BigDecimal rkje=btyWmhResult.getRkje()==null?BigDecimal.ZERO:btyWmhResult.getRkje();
                BigDecimal ckje=btyWmhResult.getCkje()==null?BigDecimal.ZERO:btyWmhResult.getCkje();
                BigDecimal ce=btyWmhResult.getCe()==null?BigDecimal.ZERO:btyWmhResult.getCe();
                String bh=btyWmhResult.getBh();
                String bm=btyWmhResult.getBm();
                //通过妖码和收发类别查询盘亏金额,统配入库金额,调拨入库金额,调拨出库金额,统配退货金额,盘盈金额
                BigDecimal pkje=BigDecimal.ZERO;
                BigDecimal tprkje=BigDecimal.ZERO;
                BigDecimal dbrkje=BigDecimal.ZERO;
                BigDecimal dbckje=BigDecimal.ZERO;
                BigDecimal tpthje=BigDecimal.ZERO;
                BigDecimal pyje=BigDecimal.ZERO;

                List<BtyWmhResult>sflbList=btyWmhService.sflbList(bm);
                for (BtyWmhResult wmhResult : sflbList) {
                    if(wmhResult.getSflb().equals("盘盈入库")){
                        pyje=wmhResult.getRkje();
                    }
                    if(wmhResult.getSflb().equals("盘亏出库")){
                        pkje=wmhResult.getCkje();
                    }
                    if(wmhResult.getSflb().equals("门店统配入库")){
                        tprkje=wmhResult.getRkje();
                    }
                    if(wmhResult.getSflb().equals("调拨入库")){
                        dbrkje=wmhResult.getRkje();
                    }
                    if(wmhResult.getSflb().equals("调拨出库")){
                        dbckje=wmhResult.getCkje();
                    }
                    if(wmhResult.getSflb().equals("门店统配退货")){
                        tpthje=wmhResult.getCkje();
                    }
                }
                //摘要取存货名称
                String chmc=btyWmhResult.getChmc();
                RestTemplate restTemplate = new RestTemplate();
                HttpHeaders headers = new HttpHeaders();
                MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
                headers.setContentType(type);
                // 档案翻译方式，枚举值为：编码请录入 code， 名称请录入 name， 主键请录入 pk
                headers.add("trantype", "code");
                // 系统编码
                headers.add("system", "001");
                // 用户
                headers.add("usercode", "15253172037");
                headers.add("password", "514576f58a89767b46c1b44767a08f77");
                headers.add("Accept", MediaType.APPLICATION_JSON.toString());

                StringBuilder sb=new StringBuilder();
                sb.append("{\n" +
                        "    \"voucher\":[\n" +
                        "        {\n" +
                        "            \"details\":[");

                //外卖盒或者发热包凭证
                /**
                 * 借：660136外卖包装费=盘亏金额
                 * 借：1403原材料=-盘亏金额+(统配入库+调拨入库-调拨出库-统配退货)
                 * 借：660110前厅低值易耗品=-(统配入库+调拨入库-调拨出库-统配退货)
                 *
                 *
                 * 借：660136外卖包装费=-盘盈金额
                 * 借：1403原材料=盘盈金额+(统配入库+调拨入库-调拨出库-统配退货)
                 * 借：660110前厅低值易耗品=-(统配入库+调拨入库-调拨出库-统配退货)
                 */
                BigDecimal ycl=tprkje.subtract(pkje).add(dbrkje).subtract(dbckje).subtract(tpthje);
                BigDecimal dzyhp=tprkje.add(dbrkje).subtract(dbckje).subtract(tpthje);

                BigDecimal pyycl=tprkje.add(pyje).add(dbrkje).subtract(dbckje).subtract(tpthje);
                BigDecimal pydzyhp=tprkje.add(dbrkje).subtract(dbckje).subtract(tpthje);


                if(pkje.compareTo(BigDecimal.ZERO)!=0) {
                    sb.append(
                            "                {\n" +
                                    "                    \"ass\":[\n" +
                                    "                        {\n" +
                                    "                            \"checktypecode\":\"2\",\n" +
                                    "                            \"checkvaluecode\":'" + yaoma + "'\n" +//借方辅助核算编码
                                    "                        }\n" +
                                    "                    ],\n" +
                                    "                    \"creditamount\":\"\",\n" +
                                    "                    \"debitamount\":\"" + pkje + "\",\n" +//借方金额
                                    "                    \"explanation\":\"" + chmc + "\",\n" +//借方摘要
                                    "                    \"localcreditamount\":\"\",\n" +
                                    "                    \"localdebitamount\":\"\",\n" +
                                    "                    \"pk_accsubj\":\"660136\",\n" +//外卖包装费科目编码
                                    "                    \"pk_currtype\":\"CNY\"\n" +
                                    "                },");
                    if(ycl.compareTo(BigDecimal.ZERO)!=0) {
                        sb.append(
                                "                {\n" +
                                        "                    \"ass\":[\n" +
                                        "                        {\n" +
                                        "                            \"checktypecode\":\"2\",\n" +
                                        "                            \"checkvaluecode\":'" + yaoma + "'\n" +
                                        "                        }\n" +
                                        "                    ],\n" +
                                        "                    \"creditamount\":\"\",\n" +
                                        "                    \"debitamount\":\"" + ycl + "\",\n" +
                                        "                    \"explanation\":\"" + chmc + "\",\n" +
                                        "                    \"localcreditamount\":\"\",\n" +
                                        "                    \"localdebitamount\":\"\",\n" +
                                        "                    \"pk_accsubj\":\"1403\",\n" +//外卖费用科目编码
                                        "                    \"pk_currtype\":\"CNY\"\n" +
                                        "                },");
                    }
                    if(dzyhp.compareTo(BigDecimal.ZERO)!=0){
                        sb.append("                {\n" +
                                "                    \"ass\":[\n" +
                                "                        {\n" +
                                "                            \"checktypecode\":\"2\",\n" +
                                "                            \"checkvaluecode\":'"+yaoma+"'\n" +
                                "                        }\n" +
                                "                    ],\n" +
                                "                    \"creditamount\":\"\",\n" +
                                "                    \"debitamount\":\"-"+dzyhp+"\",\n" +
                                "                    \"explanation\":\""+chmc+"\",\n" +
                                "                    \"localcreditamount\":\"\",\n" +
                                "                    \"localdebitamount\":\"\",\n" +
                                "                    \"pk_accsubj\":\"660110\",\n" +//原材料科目编码
                                "                    \"pk_currtype\":\"CNY\"\n" +
                                "                },");
                    }
                }


                else if(pyje.compareTo(BigDecimal.ZERO)!=0) {
                    sb.append(
                            "                {\n" +
                                    "                    \"ass\":[\n" +
                                    "                        {\n" +
                                    "                            \"checktypecode\":\"2\",\n" +
                                    "                            \"checkvaluecode\":'" + yaoma + "'\n" +//借方辅助核算编码
                                    "                        }\n" +
                                    "                    ],\n" +
                                    "                    \"creditamount\":\"\",\n" +
                                    "                    \"debitamount\":\"-" + pyje + "\",\n" +//借方金额
                                    "                    \"explanation\":\"" + chmc + "\",\n" +//借方摘要
                                    "                    \"localcreditamount\":\"\",\n" +
                                    "                    \"localdebitamount\":\"\",\n" +
                                    "                    \"pk_accsubj\":\"660136\",\n" +//外卖包装费科目编码
                                    "                    \"pk_currtype\":\"CNY\"\n" +
                                    "                },");
                    if(pyycl.compareTo(BigDecimal.ZERO)!=0) {
                        sb.append(
                                "                {\n" +
                                        "                    \"ass\":[\n" +
                                        "                        {\n" +
                                        "                            \"checktypecode\":\"2\",\n" +
                                        "                            \"checkvaluecode\":'" + yaoma + "'\n" +
                                        "                        }\n" +
                                        "                    ],\n" +
                                        "                    \"creditamount\":\"\",\n" +
                                        "                    \"debitamount\":\"" + pyycl + "\",\n" +
                                        "                    \"explanation\":\"" + chmc + "\",\n" +
                                        "                    \"localcreditamount\":\"\",\n" +
                                        "                    \"localdebitamount\":\"\",\n" +
                                        "                    \"pk_accsubj\":\"1403\",\n" +//外卖费用科目编码
                                        "                    \"pk_currtype\":\"CNY\"\n" +
                                        "                },");
                    }
                    if(pydzyhp.compareTo(BigDecimal.ZERO)!=0){
                        sb.append("                {\n" +
                                "                    \"ass\":[\n" +
                                "                        {\n" +
                                "                            \"checktypecode\":\"2\",\n" +
                                "                            \"checkvaluecode\":'"+yaoma+"'\n" +
                                "                        }\n" +
                                "                    ],\n" +
                                "                    \"creditamount\":\"\",\n" +
                                "                    \"debitamount\":\"-"+pydzyhp+"\",\n" +
                                "                    \"explanation\":\""+chmc+"\",\n" +
                                "                    \"localcreditamount\":\"\",\n" +
                                "                    \"localdebitamount\":\"\",\n" +
                                "                    \"pk_accsubj\":\"660110\",\n" +//原材料科目编码
                                "                    \"pk_currtype\":\"CNY\"\n" +
                                "                }");
                    }
                }
                /**盘盈金额和盘亏金额都等于0的情况
                 * 借：1403原材料=+(统配入库+调拨入库-调拨出库-统配退货)
                 * 借：660110前厅低值易耗品=-(统配入库+调拨入库-调拨出库-统配退货)
                 */
                else{
                    BigDecimal ycl8=tprkje.add(dbrkje).subtract(dbckje).subtract(tpthje);
                    BigDecimal dzyhp8=tprkje.add(dbrkje).subtract(dbckje).subtract(tpthje);

                    sb.append(
                            "                {\n" +
                                    "                    \"ass\":[\n" +
                                    "                        {\n" +
                                    "                            \"checktypecode\":\"2\",\n" +
                                    "                            \"checkvaluecode\":'" + yaoma + "'\n" +
                                    "                        }\n" +
                                    "                    ],\n" +
                                    "                    \"creditamount\":\"\",\n" +
                                    "                    \"debitamount\":\"" + ycl8 + "\",\n" +
                                    "                    \"explanation\":\"" + chmc + "\",\n" +
                                    "                    \"localcreditamount\":\"\",\n" +
                                    "                    \"localdebitamount\":\"\",\n" +
                                    "                    \"pk_accsubj\":\"1403\",\n" +//外卖费用科目编码
                                    "                    \"pk_currtype\":\"CNY\"\n" +
                                    "                },");
                    sb.append("                {\n" +
                            "                    \"ass\":[\n" +
                            "                        {\n" +
                            "                            \"checktypecode\":\"2\",\n" +
                            "                            \"checkvaluecode\":'"+yaoma+"'\n" +
                            "                        }\n" +
                            "                    ],\n" +
                            "                    \"creditamount\":\"\",\n" +
                            "                    \"debitamount\":\"-"+dzyhp8+"\",\n" +
                            "                    \"explanation\":\""+chmc+"\",\n" +
                            "                    \"localcreditamount\":\"\",\n" +
                            "                    \"localdebitamount\":\"\",\n" +
                            "                    \"pk_accsubj\":\"660110\",\n" +//原材料科目编码
                            "                    \"pk_currtype\":\"CNY\"\n" +
                            "                }");

                }


//                if(rkje.compareTo(BigDecimal.ZERO)!=0) {
//                    sb.append(
//                            "                {\n" +
//                                    "                    \"ass\":[\n" +
//                                    "                        {\n" +
//                                    "                            \"checktypecode\":\"2\",\n" +
//                                    "                            \"checkvaluecode\":'" + yaoma + "'\n" +//借方辅助核算编码
//                                    "                        }\n" +
//                                    "                    ],\n" +
//                                    "                    \"creditamount\":\"\",\n" +
//                                    "                    \"debitamount\":\"-" + rkje + "\",\n" +//借方金额
//                                    "                    \"explanation\":\"" + chmc + "\",\n" +//借方摘要
//                                    "                    \"localcreditamount\":\"\",\n" +
//                                    "                    \"localdebitamount\":\"\",\n" +
//                                    "                    \"pk_accsubj\":\"660110\",\n" +//前厅低值易耗品科目编码
//                                    "                    \"pk_currtype\":\"CNY\"\n" +
//                                    "                },");
//                }
//                if(ckje.compareTo(BigDecimal.ZERO)!=0) {
//                    sb.append(
//                            "                {\n" +
//                                    "                    \"ass\":[\n" +
//                                    "                        {\n" +
//                                    "                            \"checktypecode\":\"2\",\n" +
//                                    "                            \"checkvaluecode\":'" + yaoma + "'\n" +
//                                    "                        }\n" +
//                                    "                    ],\n" +
//                                    "                    \"creditamount\":\"\",\n" +
//                                    "                    \"debitamount\":\"" + ckje + "\",\n" +
//                                    "                    \"explanation\":\"" + chmc + "\",\n" +
//                                    "                    \"localcreditamount\":\"\",\n" +
//                                    "                    \"localdebitamount\":\"\",\n" +
//                                    "                    \"pk_accsubj\":\"660136\",\n" +//外卖费用科目编码
//                                    "                    \"pk_currtype\":\"CNY\"\n" +
//                                    "                },");
//                }
//                if(ce.compareTo(BigDecimal.ZERO)!=0){
//                    sb.append("                {\n" +
//                            "                    \"ass\":[\n" +
//                            "                        {\n" +
//                            "                            \"checktypecode\":\"2\",\n" +
//                            "                            \"checkvaluecode\":'"+yaoma+"'\n" +
//                            "                        }\n" +
//                            "                    ],\n" +
//                            "                    \"creditamount\":\"\",\n" +
//                            "                    \"debitamount\":\""+ce+"\",\n" +
//                            "                    \"explanation\":\""+chmc+"\",\n" +
//                            "                    \"localcreditamount\":\"\",\n" +
//                            "                    \"localdebitamount\":\"\",\n" +
//                            "                    \"pk_accsubj\":\"1403\",\n" +//原材料科目编码
//                            "                    \"pk_currtype\":\"CNY\"\n" +
//                            "                }");
//                }

                sb.append("            ],\n" +
                        "            \"pk_corp\":"+bh+",\n" +
                        "            \"pk_glorgbook\":\""+bh+"-bty01\",\n" +
                        "            \"pk_prepared\":\"15253172037\",\n" +
                        "            \"pk_vouchertype\":\"记账\",\n" +
                        "            \"prepareddate\":\""+zdrq+"\"\n" +
                        "        }\n" +
                        "    ]\n" +
                        "}");
                System.out.println("sb:"+sb.toString());
                HttpEntity<String> formEntity = new HttpEntity<String>(sb.toString(), headers);
                String url = "http://124.70.28.147:8089/u8cloud/api/gl/voucher/insert";
                String result = restTemplate.postForEntity(url, formEntity, String.class).getBody();
                System.out.println("result:"+result);
                JsonParser jp = new JsonParser();
                //将json字符串转化成json对象
                JsonObject jo = jp.parse(result).getAsJsonObject();
                //获取errcode对应的值
                String status = jo.get("status").getAsString();

                if(status.equals("falied")){
                    String errormsg = jo.get("errormsg").getAsString();
                    List<BtyWmh> wmhList=btyWmhService.list(new QueryWrapper<BtyWmh>().eq("bm",bm));
                    if(wmhList.size()>0){
                        BtyWmhParam param1=new BtyWmhParam();
                        param1.setErrormsg(errormsg);
                        param1.setBm(bm);
                        btyWmhService.updateErrMsgByDm(param1);
                    }
                }
                else{
                    List<BtyWmh> wmhList=btyWmhService.list(new QueryWrapper<BtyWmh>().eq("bm",bm));
                    if(wmhList.size()>0){
                        BtyWmhParam param1=new BtyWmhParam();
                        param1.setBm(bm);
                        btyWmhService.updateByDm(param1);
                    }
                }
            }

        }catch (Exception e) {
            e.printStackTrace();
            jsonResult.setState(0);
            jsonResult.setErrmsg(e.getMessage());
            return jsonResult;
        }
        return true;
    }

//    @RequestMapping("/listSearchExport")
//    @ResponseBody
//    public List<BtyDbdkResult> listSearchExport (BtyDbdkParam param){
//        List<BtyDbdkResult> list= btyDbdkService.customList(param);
//        return list;
//    }

}


